#include <stdio.h>
#include <string.h>
// #include <openssl/md5.h>
#include <unistd.h>
#include "../common/make_log.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>


#define CONF "/etc/fdfs/client.conf"

// void md5_encrypt(const char *data, unsigned char *result) 
// {
//     MD5_CTX ctx;
//     MD5_Init(&ctx);
//     MD5_Update(&ctx, data, strlen(data));
//     MD5_Final(result, &ctx);
// }

int trim_space(char* inbuf)
{
    int i = 0;
    int j = strlen(inbuf) - 1;

    char* str = inbuf;
    int count = 0;

    if(str == NULL)
    {
        return -1;
    }

    while(isspace(str[i]) && str[i] != '\0')
    {
        i++;
    }

    while(isspace(str[j]) && j > i)
    {
        j--;
    }

    count = j - i + 1;

    strncpy(inbuf, str + i, count);

    inbuf[count] = '\0';
    
    return 0;
}
int upload_to_dstorage(const char *filename, char *fileid)
{
    int ret = 0;
    pid_t pid;
    int fd[2];

    do
    {
        if(pipe(fd) < 0)
        {
            LOG("pipe() error!\n");
            ret = -1;
            break;
        }

        pid = fork();
        if(pid < 0)
        {
            LOG("fork error\n");
            ret = -1;
            break;
        }

        if(pid == 0)
        {
            //关闭读端
            close(fd[0]);
            dup2(fd[1], STDOUT_FILENO);

            // sleep(5);
            // execlp("fdfs_upload_file", "fdfs_upload_file", CONF, filename, NULL);

            LOG("execlp fdfs_upload_file error\n");
            
            exit(0);
        }
        else
        {
            close(fd[1]);

            read(fd[0], fileid, 512);

            LOG("fileid = %s\n", fileid);
            trim_space(fileid);
            LOG("fileid = %s\n", fileid);

            if(strlen(fileid) == 0)
            {
                LOG("ipload failed! \n");
                ret = -1;
                break;
            }

            LOG("get [%s] success!\n", fileid);

            close(fd[0]);
        }
    }while(0);

    wait(NULL);
    return ret;
}
char t[512] = {0};


void fun()
{
    printf("%ld\n", sizeof(t));
    
}

int main(void) 
{
    // char * s = "Ljs1536637832";
    // unsigned char result[MD5_DIGEST_LENGTH] = {0};

    // md5_encrypt(s, result);

    // char str[100] = {0};
    // char token[100] = {0};
    // for (int i = 0; i < MD5_DIGEST_LENGTH; i++) 
    // {
    //     sprintf(str, "%02x", result[i]);
    //     strcat(token, str);
    // }
    
    // printf("%s\n", token);

    // char fileid[512] = {0};

    // const char* a = "C++.txt";

    // upload_to_dstorage(a, fileid);



    char filename[100] = {0};
    char fileid[100] = {0};
    // fun();

    upload_to_dstorage(filename, fileid);
    return 0;
}